package com.bite.captchademo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.bite.captchademo.model.CaptchaProperties;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;

    private Long VALID_TIME;
    @PostConstruct
    public void init() {
        // 必须在创建对象后才能使用 不然就有空指针异常
        VALID_TIME =  captchaProperties.getSession().getValidTime();
    }

    // 获取验证码
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        try {
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
            lineCaptcha.write(response.getOutputStream());
            // 禁用缓存
            response.setHeader("Prama", "No-cache");
            // 设置返回类型
            response.setContentType("image/jpeg");

            System.out.println(lineCaptcha.getCode());
            // 设置到 Session 中
            session.setAttribute(captchaProperties.getSession().getCodeKey(), lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getTimeKey(), System.currentTimeMillis());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    // 校验验证码
    @RequestMapping("/check")
    public Boolean check(String code, HttpSession session) {
        System.out.println(code);
        if (session.getAttribute(captchaProperties.getSession().getCodeKey()) == null || code == null) {
            return false;
        }
        // 判断
        Long thatTime = (Long) session.getAttribute(captchaProperties.getSession().getTimeKey());
        if ((thatTime == null || System.currentTimeMillis() - thatTime <= VALID_TIME)
                && code.equals(session.getAttribute(captchaProperties.getSession().getCodeKey()))) {
            return true;
        }
        return false;
    }
}

